package dialog.program;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("rawtypes")
class User
{
	int userCode;
	String name;
	String address;
	String phoneNumber;
	Collection loans = new LinkedList();
	static Map usedPositions = new HashMap();

	@SuppressWarnings("unchecked")
	public User(String name, String address, String phoneNumber)
	{
		int nextUserCodeAvailable = 0;
		this.name = name;
		this.address = address;
		this.phoneNumber = phoneNumber;
		userCode = nextUserCodeAvailable++;
		while (usedPositions.containsValue(userCode))
		{
			userCode++;
			nextUserCodeAvailable++;			
		}
		usedPositions.put(userCode, userCode);
	}
	
	public void removePosition(int position)
	{
		usedPositions.remove(position);
	}
	
	@SuppressWarnings("unchecked")
	public User(String name, String address, String phoneNumber, String ID)
	{
		this.name = name;
		this.address = address;
		this.phoneNumber = phoneNumber;
		this.userCode = Integer.parseInt(ID) - 1;
		usedPositions.put(userCode, userCode);
	}

	public boolean equals(Object obj)
	{
		User user = (User) obj;
		return userCode == user.userCode;
	}
	
	public boolean authorizedUser()
	{
		return false;
	}
	
	public int getCode()
	{
		return userCode;
	}
	
	public String getName()
	{
		return name;
	}
	
	public String getAddress()
	{
		return address;
	}

	public String getPhone()
	{
		return phoneNumber;
	}

	@SuppressWarnings("unchecked")
	public void addLoan(Loan loan)
	{
		loans.add(loan);
	}
	
	public int numberOfLoans()
	{
		return loans.size();
	}
	
	public void removeLoan(Loan loan)
	{
		loans.remove(loan);
	}

	public void printInfo(HttpServletResponse response)
		throws IOException, ServletException
	{
		PrintWriter writer = response.getWriter();
		writer.println("<center><b>User Profile:</b><br><br>");
		writer.println("<table style=\"text-align: left; width: 140px; height: 100px;" +
			"border=\"1\" cellpadding=\"2\" cellspacing=\"2\"\">" +
			"<tbody>" +
			"<tr>" +
				"<td><b>User ID: </b></td>" +
				"<td>" + (getCode() + 1) + "</td>" +
			"</tr>" +
			"<tr>" +
				"<td><b>Name: </b></td>" +
				"<td>" + getName() + "</td>" +
			"</tr>" +
			"<tr>" +
				"<td><b>Address: </b></td>" +
				"<td>" + getAddress() + "</td>" +
			"</tr>" +
			"<tr>" +
				"<td><b>Phone: </b></td>" +
				"<td>" + getPhone() + "</td>" +
			"</tr>" +
			"</tbody>" +
			"</table></center>");
		if (loans.size() != 0);
		{
			if(loans.size() != 0)
				writer.println("<br><b>Borrowed documents: </b><br>");
			Iterator i = loans.iterator();
			while (i.hasNext())
			{
				Loan loan = (Loan)i.next();
				Document doc = loan.getDocument();
				writer.println("Document ID: <b>" + (doc.getCode() + 1) + "</b><br>");
				writer.println("Type: <b>" + doc.getType() + "</b><br>");
				writer.println("Title: <b>\"" + doc.getTitle() + "\"</b><br><br>");
			}
			writer.println("</center>");
		}
	}
}